﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using netCoreStudy.Dto.User;
using netCoreStudy.Entities;
using netCoreStudy.Entities.Base;
using netCoreStudy.Entities.Parameter;
using netCoreStudy.Helper;
using netCoreStudy.IService;
using static netCoreStudy.MyCommonMethod;

namespace netCoreStudy.Controllers
{
	/// <summary>
	/// 用户管理 
	/// </summary>
	[ApiController]
	[Route("api/user")]
	public class UserController : BaseController<User, UserDto, UserParameter, AddUserDto, UpdateUserDto>
	{
		private readonly IUserService _userService;

		public UserController(ILogger<UserController> logger, IBaseService<User> baseService, IMapper mapper,
			IUserService userService)
			: base(logger, baseService, mapper)
		{
			_userService = userService;
		}


		protected override AddUserDto SolveAddDto(AddUserDto dto)
		{
			string password = dto.Password;
			// 加密
			dto.Password = Md5Encrypt32(password);
			return dto;
		}


		/// <summary>
		///  根据token获取用户详情
		/// </summary>
		/// <param name="token"></param>
		/// <returns></returns>
		[HttpGet("getInfoByToken")]
		public async Task<IActionResult> GetInfoByToken(string token)
		{
			if (!token.IsNotEmptyOrNull())
			{
				return this.FailMsg("token为空!");
			}

			TokenModelJwt tokenModel = JwtHelper.SerializeJwt(token);
			if (tokenModel == null || tokenModel.Uid <= 0) return this.FailMsg("解析token 解析不出来!");
			User user = await _userService.GetOneByIdAsync(tokenModel.Uid);
			return user == null
				? this.FailMsg("解析的token对应的用户不存在!")
				: this.SuccessMsg("解析token成功!", _mapper.Map<UserDto>(user));
		}

		/// <summary>
		///  根据token获取用户详情
		/// </summary>
		/// <param name="token"></param>
		/// <returns></returns>
		[HttpGet("Test")]
		public async Task<IActionResult> Test(string token)
		{
			await _userService.GetAll().ToListAsync();
			

			return this.SuccessMsg("成功");
		}
				
	}
}

